/**
 * 知识图谱实体关系网络管理模块
 */

let knowledgeRelationAPI_BASE = '/api/feibiao/knowledge/relation';

document.addEventListener('DOMContentLoaded', function() {
    if (typeof API_BASE !== 'undefined') {
        knowledgeRelationAPI_BASE = `${API_BASE}/feibiao/knowledge/relation`;
    }
});

function loadKnowledgeRelationList(page = 0, size = 10) {
    const mainContent = document.getElementById('mainContent');
    if (!mainContent) return;
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    fetch(`${knowledgeRelationAPI_BASE}?page=${page}&size=${size}&sort=relationshipId,asc`)
        .then(response => {
            if (!response.ok) throw new Error('请求失败: ' + response.statusText);
            return response.json();
        })
        .then(data => {
            renderKnowledgeRelationTable(data);
        })
        .catch(error => {
            mainContent.innerHTML = `<div class="error-container">加载失败: ${error.message}</div>`;
            showMessage('获取实体关系数据失败: ' + error.message, 'error');
        });
}

function renderKnowledgeRelationTable(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">实体关系网络管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showKnowledgeRelationForm()"></i> 新增</button>
            </div>
        </div>
        <div class="content-toolbar">
            <div class="search-box">
                <input type="text" class="search-input" id="relationEntityId1Input" placeholder="起始实体ID...">
                <input type="text" class="search-input" id="relationEntityId2Input" placeholder="目标实体ID...">
                <input type="text" class="search-input" id="relationTypeInput" placeholder="关系类型...">
                <button class="search-btn" onclick="searchKnowledgeRelation()">搜索</button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>起始实体ID</th>
                        <th>目标实体ID</th>
                        <th>关系类型</th>
                        <th>关系说明</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.relationshipId}</td>
                    <td>${item.entityId1}</td>
                    <td>${item.entityId2}</td>
                    <td>${item.relationshipType}</td>
                    <td>${item.relationshipDescription}</td>
                    <td>${formatDate(item.relationUpdateTime)}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewKnowledgeRelation('${item.relationshipId}')">查看</a>
                        <a href="javascript:void(0)" onclick="editKnowledgeRelation('${item.relationshipId}')">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteKnowledgeRelation('${item.relationshipId}')">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="7" style="text-align:center;">暂无数据</td></tr>';
    }
    html += `</tbody></table></div>`;
    
    // 添加分页控件 - 仿照knowledge_basic.js的分页样式
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${data.number <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number <= 0 ? 'void(0)' : 'loadKnowledgeRelationList(' + (data.number - 1) + ', ' + data.size + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === data.number) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadKnowledgeRelationList(${i}, ${data.size})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${data.number >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number >= data.totalPages - 1 ? 'void(0)' : 'loadKnowledgeRelationList(' + (data.number + 1) + ', ' + data.size + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    mainContent.innerHTML = html;
}

function searchKnowledgeRelation() {
    const entityId1 = document.getElementById('relationEntityId1Input').value.trim();
    const entityId2 = document.getElementById('relationEntityId2Input').value.trim();
    const relationshipType = document.getElementById('relationTypeInput').value.trim();
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据搜索中...</div>';
    let url = `${knowledgeRelationAPI_BASE}/search?`;
    if (entityId1) url += `entityId1=${encodeURIComponent(entityId1)}&`;
    if (entityId2) url += `entityId2=${encodeURIComponent(entityId2)}&`;
    if (relationshipType) url += `relationshipType=${encodeURIComponent(relationshipType)}&`;
    url += 'sort=relationshipId,asc';
    fetch(url)
        .then(response => {
            if (!response.ok) throw new Error('搜索请求失败: ' + response.statusText);
            return response.json();
        })
        .then(data => {
            renderKnowledgeRelationTable(data);
        })
        .catch(error => {
            mainContent.innerHTML = `<div class="error-container">搜索失败: ${error.message}</div>`;
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

function showKnowledgeRelationForm(data = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = !!data;
    let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}实体关系</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadKnowledgeRelationList()"><i class="fa fa-arrow-left"></i> 返回列表</button>
            </div>
        </div>
        
        <div class="form-container">
            <form id="knowledgeRelationForm" class="data-form" onsubmit="submitKnowledgeRelationForm(event)">
                ${isEdit ? `<input type="hidden" id="relationshipId" name="relationshipId" value="${data.relationshipId}">` : ''}
                
                <div class="form-section">
                    <h3 class="section-title">基本信息</h3>
                    
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="entityId1">起始实体ID <span class="required">*</span></label>
                            <input type="text" id="entityId1" name="entityId1" class="form-control" 
                                maxlength="20" value="${isEdit ? data.entityId1 : ''}" 
                                placeholder="输入起始实体ID，例如：E001" required>
                            <small class="form-text">实体关系的起始点，必须是已存在的实体ID</small>
                        </div>
                        
                        <div class="form-group col-md-6">
                            <label for="entityId2">目标实体ID <span class="required">*</span></label>
                            <input type="text" id="entityId2" name="entityId2" class="form-control" 
                                maxlength="20" value="${isEdit ? data.entityId2 : ''}" 
                                placeholder="输入目标实体ID，例如：E002" required>
                            <small class="form-text">实体关系的目标点，必须是已存在的实体ID</small>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="relationshipType">关系类型 <span class="required">*</span></label>
                        <select id="relationshipType" name="relationshipType" class="form-control" required>
                            <option value="" disabled ${!isEdit ? 'selected' : ''}>请选择关系类型...</option>
                            <option value="包含" ${isEdit && data.relationshipType === '包含' ? 'selected' : ''}>包含</option>
                            <option value="属于" ${isEdit && data.relationshipType === '属于' ? 'selected' : ''}>属于</option>
                            <option value="组成" ${isEdit && data.relationshipType === '组成' ? 'selected' : ''}>组成</option>
                            <option value="引用" ${isEdit && data.relationshipType === '引用' ? 'selected' : ''}>引用</option>
                            <option value="控制" ${isEdit && data.relationshipType === '控制' ? 'selected' : ''}>控制</option>
                            <option value="依赖" ${isEdit && data.relationshipType === '依赖' ? 'selected' : ''}>依赖</option>
                            <option value="其他" ${isEdit && !['包含', '属于', '组成', '引用', '控制', '依赖'].includes(data.relationshipType) ? 'selected' : ''}>其他</option>
                        </select>
                        <small class="form-text">表示两个实体之间的关系类型</small>
                        <div id="otherRelationshipTypeContainer" style="display: none; margin-top: 10px;">
                            <input type="text" id="otherRelationshipType" class="form-control" 
                                placeholder="请输入自定义关系类型" 
                                value="${isEdit && !['包含', '属于', '组成', '引用', '控制', '依赖'].includes(data.relationshipType) ? data.relationshipType : ''}">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="relationshipDescription">关系说明 <span class="required">*</span></label>
                        <textarea id="relationshipDescription" name="relationshipDescription" 
                            class="form-control" rows="4" 
                            placeholder="请详细描述这两个实体之间的关系..." required>${isEdit ? data.relationshipDescription : ''}</textarea>
                        <small class="form-text">详细描述该关系的具体含义和重要性，不少于10个字</small>
                    </div>
                </div>
                
                <div class="form-section">
                    <h3 class="section-title">附加信息</h3>
                    
                    <div class="form-group">
                        <label for="relationStrength">关系强度</label>
                        <select id="relationStrength" name="relationStrength" class="form-control">
                            <option value="" ${!isEdit || !data.relationStrength ? 'selected' : ''}>-- 请选择 --</option>
                            <option value="强" ${isEdit && data.relationStrength === '强' ? 'selected' : ''}>强</option>
                            <option value="中" ${isEdit && data.relationStrength === '中' ? 'selected' : ''}>中</option>
                            <option value="弱" ${isEdit && data.relationStrength === '弱' ? 'selected' : ''}>弱</option>
                        </select>
                        <small class="form-text">表示两个实体之间关联的紧密程度（可选）</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="relationRemarks">备注信息</label>
                        <textarea id="relationRemarks" name="relationRemarks" class="form-control" rows="2"
                            placeholder="其他补充信息...">${isEdit && data.relationRemarks ? data.relationRemarks : ''}</textarea>
                        <small class="form-text">可以添加关于此关系的其他补充说明（可选）</small>
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> ${isEdit ? '保存修改' : '创建关系'}
                    </button>
                    <button type="button" class="btn btn-default" onclick="loadKnowledgeRelationList()">
                        <i class="fa fa-times"></i> 取消
                    </button>
                </div>
            </form>
        </div>
    `;
    
    mainContent.innerHTML = html;
    
    // 处理"其他"关系类型的显示/隐藏逻辑
    const relationshipTypeSelect = document.getElementById('relationshipType');
    const otherRelationshipTypeContainer = document.getElementById('otherRelationshipTypeContainer');
    
    function updateOtherRelationshipTypeVisibility() {
        if (relationshipTypeSelect.value === '其他') {
            otherRelationshipTypeContainer.style.display = 'block';
        } else {
            otherRelationshipTypeContainer.style.display = 'none';
        }
    }
    
    // 初始化时检查
    updateOtherRelationshipTypeVisibility();
    
    // 添加change事件监听器
    relationshipTypeSelect.addEventListener('change', updateOtherRelationshipTypeVisibility);
}

function submitKnowledgeRelationForm(event) {
    event.preventDefault();
    
    // 获取表单字段值
    const id = document.getElementById('relationshipId')?.value;
    const entityId1 = document.getElementById('entityId1').value.trim();
    const entityId2 = document.getElementById('entityId2').value.trim();
    
    // 处理关系类型，如果选择"其他"则使用自定义输入
    let relationshipType = document.getElementById('relationshipType').value;
    if (relationshipType === '其他') {
        relationshipType = document.getElementById('otherRelationshipType').value.trim();
        
        // 验证自定义关系类型不能为空
        if (!relationshipType) {
            showMessage('请输入自定义关系类型', 'error');
            document.getElementById('otherRelationshipType').focus();
            return;
        }
    }
    
    const relationshipDescription = document.getElementById('relationshipDescription').value.trim();
    const relationStrength = document.getElementById('relationStrength').value;
    const relationRemarks = document.getElementById('relationRemarks').value.trim();
    
    // 表单验证
    if (!entityId1) {
        showMessage('请输入起始实体ID', 'error');
        document.getElementById('entityId1').focus();
        return;
    }
    
    if (!entityId2) {
        showMessage('请输入目标实体ID', 'error');
        document.getElementById('entityId2').focus();
        return;
    }
    
    if (entityId1 === entityId2) {
        showMessage('起始实体ID和目标实体ID不能相同', 'error');
        document.getElementById('entityId2').focus();
        return;
    }
    
    if (!relationshipType) {
        showMessage('请选择或输入关系类型', 'error');
        document.getElementById('relationshipType').focus();
        return;
    }
    
    if (!relationshipDescription) {
        showMessage('请输入关系说明', 'error');
        document.getElementById('relationshipDescription').focus();
        return;
    }
    
    if (relationshipDescription.length < 10) {
        showMessage('关系说明不能少于10个字', 'error');
        document.getElementById('relationshipDescription').focus();
        return;
    }
    
    // 构建数据对象
    const data = {
        entityId1,
        entityId2,
        relationshipType,
        relationshipDescription
    };
    
    // 添加可选字段
    if (relationStrength) {
        data.relationStrength = relationStrength;
    }
    
    if (relationRemarks) {
        data.relationRemarks = relationRemarks;
    }
    
    // 如果是编辑操作，添加ID字段
    if (id) {
        data.relationshipId = id;
    }
    
    // 显示加载提示
    showMessage('正在保存数据...', 'info');
    
    // 确定请求方法和URL
    const method = id ? 'PUT' : 'POST';
    const url = id ? `${knowledgeRelationAPI_BASE}/${id}` : knowledgeRelationAPI_BASE;
    
    // 发送请求
    fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                try {
                    const error = JSON.parse(text);
                    throw new Error(error.message || error.error || '保存失败');
                } catch (e) {
                    throw new Error(text || '保存失败');
                }
            });
        }
        return response.json();
    })
    .then(result => {
        showMessage(`关系${id ? '更新' : '创建'}成功!`, 'success');
        loadKnowledgeRelationList();
    })
    .catch(error => {
        console.error('保存失败:', error);
        showMessage('保存失败: ' + error.message, 'error');
    });
}

function viewKnowledgeRelation(id) {
    fetch(`${knowledgeRelationAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) throw new Error('获取详情失败: ' + response.statusText);
            return response.json();
        })
        .then(data => {
            showKnowledgeRelationDetail(data);
        })
        .catch(error => {
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

function showKnowledgeRelationDetail(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">实体关系详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadKnowledgeRelationList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        <div class="data-detail">
            <div class="detail-group"><label>ID:</label><div>${data.relationshipId || '--'}</div></div>
            <div class="detail-group"><label>起始实体ID:</label><div>${data.entityId1 || '--'}</div></div>
            <div class="detail-group"><label>目标实体ID:</label><div>${data.entityId2 || '--'}</div></div>
            <div class="detail-group"><label>关系类型:</label><div>${data.relationshipType || '--'}</div></div>
            <div class="detail-group"><label>关系说明:</label><div>${data.relationshipDescription || '--'}</div></div>
            <div class="detail-group"><label>更新时间:</label><div>${formatDate(data.relationUpdateTime) || '--'}</div></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editKnowledgeRelation('${data.relationshipId}')"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteKnowledgeRelation('${data.relationshipId}')"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadKnowledgeRelationList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    mainContent.innerHTML = html;
}

function editKnowledgeRelation(id) {
    fetch(`${knowledgeRelationAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) throw new Error('获取数据失败: ' + response.statusText);
            return response.json();
        })
        .then(data => {
            showKnowledgeRelationForm(data);
        })
        .catch(error => {
            showMessage('获取数据失败: ' + error.message, 'error');
        });
}

function deleteKnowledgeRelation(id) {
    if (!confirm('确定要删除这条关系吗？此操作不可恢复！')) return;
    fetch(`${knowledgeRelationAPI_BASE}/${id}`, { method: 'DELETE' })
        .then(response => {
            if (!response.ok) throw new Error('删除失败: ' + response.statusText);
            showMessage('删除成功!', 'success');
            loadKnowledgeRelationList();
        })
        .catch(error => {
            showMessage('删除失败: ' + error.message, 'error');
        });
}

function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

function showMessage(msg, type) {
    if (typeof window.showMessage === 'function') {
        window.showMessage(msg, type);
        return;
    }
    alert(msg);
} 